
// gen一个随机数值串出来
function genRandCode (leng) {
  if (String(typeof leng).toLocaleLowerCase() === 'number') return Math.random().toFixed(leng).toString().replace(/\d\./, '')
  else {
    throw new Error(`收到类型不为数值的参数：${leng} | ${String(typeof leng).toLocaleLowerCase()}。无法产生指定长度随机数`)
  }
}
// gen一个随机字母串出来
function genRandEngCode (leng) {
  let result = ''
  let i = 0
  const tempArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  if (String(typeof leng).toLocaleLowerCase() === 'number') {
    while (i < leng) {
      let randomNum = ~~(Math.random() * 26)
      result += tempArr[randomNum]
      i++
    }
    return result
  } else {
    throw new Error(`收到类型不为数值的参数：${leng} | ${String(typeof leng).toLocaleLowerCase()}。无法产生指定长度随机数`)
  }
}
/**
 * 截取指定长度的数值字符串
 * @param {string|number} num 要截取的数字基础
 * @param {number} leng 截取长度
 * @return {string} 返回指定长度的数值字符串
 */
function addPreZero (num, leng) {
  let tempStr = ''
  let i = 0
  while (i < leng) {
    tempStr += '0'
    i++
  }
  return (`${tempStr}${num}`).slice(-leng)
}

// 生成uid
$('.id[p-uid]').each((index, item) => {
  let leng = 5
  let rawID = ''
  if ($(item).attr('p-uid')) rawID = $(item).attr('p-uid').replace(/\D/g, '')
  else {
    return
  }
  let resultID = ''
  const rawIDAlt = addPreZero(rawID, leng)
  resultID = sessionStorage.getItem(`pro_id${rawID}`) || `A${genRandEngCode(1)}${genRandCode(1)}${rawIDAlt.substr(0, 4)}${genRandCode(2)}${rawIDAlt.substr(-1)}`
  $(item).text(resultID)
  sessionStorage.setItem(`pro_id${rawID}`, resultID)
})

function getNewMessage () {
  /**
   * 获取最新数据接口 {:U('Chat/update_record')} 返回最新一条或者几条数据  条件 chat_id,record_id(记录id)
   */
  const chatID = String($('#getRoomID').val())
  const recordID = $(`.messageBlock[inori-data-id]:eq(-1)`).attr('inori-data-id')
  const ajaxURL = String($(`#getMessage`).val())
  const phpVar = JSON.parse(window.fromPHP)
  const messageFrom = phpVar.from_user_group_id
  if (recordID === '' || recordID === undefined) {
    if (/[\d\w\.，。：]/m.test($('#messageInput').text())) {
      $.toptip(`检查到输入框存在内容，延后刷新拉取`, 'success')
      return
    }
    $.toptip(`未找到消息id, 正在准备刷新页面以便服务器渲染`, 'success')
    setTimeout(() => {
      location.href = `${location.href}?front_end_not_submit=${Math.random()}`
    }, 1000);
    return
  }
  const ajaxData = {
    chat_id: chatID,
    record_id: recordID,
    to_user_group_id: messageFrom
  }
  $.ajax(ajaxURL, {
    method: 'post',
    data: ajaxData,
    beforeSend: () => {
      $.toptip('正在拉取消息', 'success')
    }
  }).fail((err) => {
    $.toptip(`消息拉取失败，请检查网络`, 'error')
  }).done((res) => {
    if (res.code && (String(res.code) !== '1' && String(res.code) !== '2')) {
      // 失败
      $.toptip(`消息拉取失败，服务器返回: ${res.message}`, 'error')
      console.error(`消息拉取失败，服务器返回: ${res.message}`)
    } else if (res.code === undefined) {
      // 失败
      $.toptip(`消息拉取失败，服务器返回未知格式`, 'error')
      console.error(`消息拉取失败，服务器返回: ${res}`)
    }
  }).done((res) => {
    if (String(res.code) === '1') {
      $.toptip(`发现${res.data.length}条新消息，正在处理。。。`, 'success')
      $.each(res.data, (index, item) => {
        const MessageBlockString = genMessageBlockString(item)
        $('.messageContainer').append(MessageBlockString)
        // 计算所有对话框的高度，高度*2作为滚动距离，保证滚动到末尾
        let scrollLength = 0
        $('.message_main_block').each((index, item) => {
          scrollLength += $(item).height()
        })
        $('.messageContainer').scrollTop(scrollLength * 10086)
      })
    } else if (String(res.code) === '2') {
      $.toptip(`没有发现新消息`, 'success')
    }
  })
}

function genMessageBlockString (item) {
  const cahtID = item.chatID
  const fromUser = item.from_user
  const msg = item.msg
  const recordID = item.record_id
  const sendTime = item.send_time
  const spaceTime = item.space_time
  const time = item.time.replace(/:\d\d$/, '')
  const to_user = item.to_user
  const templ = `
    <div class="messageBlock" inori-data-id='${recordID}'>
      <div class="person_logo">
        <div class="name my_name">渠</div>
      </div>
      <div class="message_main_block">
        <div class="person_name">渠道昵称</div>
        <div class="person_name anjie_from">炒鸡牛逼贷公司</div>
        <div class="his_name">我</div>
        <div class="message_content">${msg}</div>
        <div class="message_time">${time}</div>
      </div>
    </div>
  `.trim()
  return templ
}

/**
 * @description 文件上传处理函数
 * @param {JQuery.Event<any>} evt
 */
function fileUploadHandle (evt) {
  if($(evt.target)[0].files.length === 0) {
    return
  }
  const ajaxURL = String($('#fileUploadAjaxURL').val())
  const item = $(evt.target)[0].files[0]
  let shouldReturn = false
  let shouldRemain = false
  $.each($(evt.target)[0].files, (index, item) => {
    // if(item.size > 2100000) {
    //   $.toptip('文件过大！请选择2MB以下的文件','error')
    //   shouldReturn = true
    //   return
    // }
    if(item.size > 200000) {
      shouldRemain = true
    }
  })
  if (shouldRemain && !shouldReturn) {
    const flag = confirm('文件体积超过200KB，上传耗时较长，确定上传？')
    if(!flag) {
      $.toptip('取消上传','success')
      shouldReturn = true
    }
  }
  if(shouldReturn) {
    $(evt.target).val(null).change()
    return
  }
  $(`#file_upload_popup`).popup()
  new Promise((resolve, reject) => {
    let formFile = new FormData();
    // 一定要append一个文本值
    formFile.append("action", "Uh");
    formFile.append("file", item); //加入文件对象
    // alert($('#file_upload').get(0).files[0] === item)
    $.ajax(ajaxURL, {
      method: 'post',
      data: formFile,
      processData:false,
      dataType:"json",
      contentType: false,
      beforeSend: () => {
        $.toptip(`正在上传文件：${item.name}, 请等待`, 'success')
      }
    }).fail((err) => {
      console.dir(err)
      reject(err)
    }).done((res) => {
      if(res.message && (String(res.code) === '2' || String(res.code) === '3')) {
        $.toptip(`上传文件失败，服务器返回：${res.message}`, 'error')
        reject(new Error(`上传文件失败，服务器返回：${res.message}`))
      } else if (String(res.code) === '2' || String(res.code) === '3') {
        $.toptip(`上传文件失败，服务器返回：${res}`, 'error')
        reject(new Error(`上传文件失败，服务器返回：${res}`))
      } else {
        resolve(res)
      }
    })
  }).then(res => {
    return new Promise((resolve, reject) => {
      const ajaxURL = `${$(`#save_img`).val()}`
      const dataFromPHP = $($.parseXML(window.chat_lccdc_data))
      const c_id = dataFromPHP.find('c_id').text()
      const add_link = res.link
      const ajaxData = {
        c_id: c_id,
        add_link: add_link
      }
      $.ajax(ajaxURL, {
        type: 'post',
        data: ajaxData,
        timeout: 1200
      }).fail((err, errType) => {
        let Err = {}
        if (`${errType}` === 'timeout') Err = new Error(`timeout`)
        else Err = err
        reject(Err)
      }).done(res => {
        if(!res.code) {
          reject(new Error(`${res}`))
        } else if(`${res.code}` !== '1') {
          reject(new Error(`${JSON.stringify(res)}`))
        } else {
          resolve(res)
        }
      })
    })
  }).then( _ => {
    $.closePopup()
    $.confirm({
      title: '上传完成',
      text: '是否继续补充客户图片？',
      // buttons: [
      //   { text: "继续上传", onClick: function(){ console.log(1)} },
      //   { text: "上传完毕", className: "default", onClick: function(){ console.log(2)} },
      // ],
      onOK: () => {
        $('#js-add_more_img_input').val(null)
        setTimeout(() => {
          $('#js-add_more_img_input').click()
        }, 0)
      },
      onCancel: () => {
        location.reload(true)
      }
    })
  }).catch(err => {
    $.closePopup()
    $.confirm({
      title: '上传失败',
      text: '是否重试补充客户图片？',
      // buttons: [
      //   { text: "我要重试", onClick: function(){ console.log(1)} },
      //   { text: "取消", className: "default", onClick: function(){ console.log(2)} },
      // ],
      onOK: () => {
        $('#js-add_more_img_input').val(null)
        setTimeout(() => {
          $('#js-add_more_img_input').click()
        }, 0)
      },
      onCancel: () => {
        // location.reload(true)
        $.toptip('取消上传', 'success')
      }
    })
  })
}
/**
 * @description 文件上传点击处理函数，主要就是“转发”一下点击动作
 * @param {JQuery.Event<any>} evt
 */
function addMorePictureHandle (evt) {
  evt.preventDefault()
  $('#js-add_more_img_input').click()
}

$(document).ready(() => {
  // 还原客户消息
  const dataFromPHP = $($.parseXML(window.chat_lccdc_data))
  const kehuName = dataFromPHP.find('kehu_name').text()
  const kehuData = dataFromPHP.find('data').text()
  const kehuLink = dataFromPHP.find('link').text()
  let templList = ``
  // 清除可能存在的多余元素
  $(`#panel_data_container .weui-cell`).each((index, item) => {
    $(item).remove()
  })
  templList += `
    <div class="weui-cell">
      <div class="weui-cell__bd">
        <p>客户姓名</p>
      </div>
      <div class="weui-cell__ft">${kehuName}</div>
    </div>
  `.trim()
  $.each(JSON.parse(kehuData), (index, item) => {
    const conventObj = {
      'kehu_edu':'贷款需求',
      'kehu_plan_point':'预计佣金点数',
      'kehu_shouru_way':'收入方式',
      'danwei_xingzhi':'单位性质',
      'business_lic':'营业执照年限',
      'social_sec':'社保年限',
      'fund_time':'公积金年限',
      'danwei_work_time':'现单位工作时长',
      'pay_way':'工资方式',
      'pay_source':'现单位工资金额',
      'avg_cost':'平均月流水',
      'register':'户籍',
      'kehu_more':'补充说明'
    }
    if (item.name === 'kehu_edu') {
      const templ = `
        <div class="weui-cell">
          <div class="weui-cell__bd">
            <p>${conventObj[item.name]}</p>
          </div>
          <div class="weui-cell__ft">${item.value}万</div>
        </div>
      `.trim()
      templList += templ
    } else {
      const templ = `
        <div class="weui-cell">
          <div class="weui-cell__bd">
            <p>${conventObj[item.name]}</p>
          </div>
          <div class="weui-cell__ft">${item.value}</div>
        </div>
      `.trim()
      templList += templ
    }
  })

  // 还原渠道信息
  {
    const ajaxURL = String($(`#getQudaoList`).val())
    const ajaxData = {
      chat_id: String($(`#getRoomID`).val())
    }
    new Promise((resolve, reject) => {
      $.ajax(ajaxURL, {
        method: 'post',
        data: ajaxData,
        timeout: 3000,
      }).fail((err, errType) => {
        let Err = {}
        if (`${errType}` === 'timeout') Err = new Error(`timeout`)
        else Err = err
        reject(Err)
      }).done((res) => {
        if (res.code && String(res.code) !== '1') {
          // 失败
          $.toptip(`人员列表获取失败，服务器返回: ${res.message}`, 'error')
          console.error(`人员列表获取失败，服务器返回: ${res.message}`)
          reject(new Error(`人员列表获取失败，服务器返回: ${res.message}`))
        } else if (res.code === undefined) {
          // 失败
          $.toptip(`人员列表获取失败，服务器返回未知格式`, 'error')
          console.error(`人员列表获取失败，服务器返回: ${res}`)
          reject(new Error(`人员列表获取失败，服务器返回: ${res}`))
        }
      }).done((res) => {
        const peopleList = res.data
        let uniPeopleList = []
        // 异步数组
        let promiseArrayObj = {
          promiseArrayPro: [],
          promiseArrayQudao: [],
          qudaoList: []
        }
        // 去重
        $.each(peopleList, (index, item) => {
          if(uniPeopleList.findIndex((value) => String(value.cg_id) === String(item.cg_id)) === -1) uniPeopleList.push(item)
        })
        $.each(uniPeopleList, (index, item) => {
          // 白经理 - 龙岗区 1.78~2.38 2万~33万
          promiseArrayObj.qudaoList.push({
            to_user_group_id: item.to_user_group_id, // 渠道聊天室的id
            region_web_city_id: item.region_web_city_id, // 区
            region_web_area_id: item.region_web_area_id, // 市
            web_name: item.web_name, // 渠道全名
            web_phone: item.web_phone, // 渠道手机
            goods_id: item.goods_id, // 渠道手机
          })
          // 产品id换产品信息
          promiseArrayObj.promiseArrayPro.push( new Promise((resolve, reject) => {
            $.ajax(String($(`#ajax_leaxnm`).val()), {
              data: {gid: `${item.goods_id}`},
              timeout: 1500, //超时时间设置，单位毫秒
              beforeSend: () => {
                // if (window.__currentFetchQudaoList) clearTimeout(window.__currentFetchQudaoList)
                // if (window.__currentFetchQudaoListIndex) {
                //   window.__currentFetchQudaoListIndex = ++window.__currentFetchQudaoListIndex
                // } else {
                //   window.__currentFetchQudaoListIndex = 1
                // }
                // window.__currentFetchQudaoList = setTimeout(() => {
                //   $.toptip(`正在获取第${window.__currentFetchQudaoListIndex}个渠道的产品利息信息`, 'success')
                // }, 300)
              }
            }).fail((err, errType) => {
              if (`${errType}` === 'timeout') reject(new Error(`timeout`))
              else reject(err)
            }).done((res) => {
              if(!res.code || `${res.code}` !== '1') {
                reject(new Error(JSON.stringify(res)))
              } else (
                resolve(res)
              )
            })
          }) )
        })
        resolve(promiseArrayObj)
      })
    }).then( (promiseObj) => {
      return Promise.all(promiseObj.promiseArrayPro).then((dataArray) => {
        $.each(dataArray, (index, item) => {
          promiseObj.qudaoList[index] = Object.assign({}, promiseObj.qudaoList[index], item.data)
        })
        // 替换处理渠道信息窗口
        $.each(promiseObj.qudaoList, (index, item) => {
          const chat_id = item.to_user_group_id
          $.each($(`[js-chat-id="${chat_id}"]`), (_index, _item) => {
            const _target = $(_item)
            // if (_target.attr('js-is-anjie') === '1') {
            if (window.isAnjie) {
              _target.text(`${item.web_name} - ${item.region_web_city_id}${item.region_web_area_id}`)
              _target.after(_target.clone().removeAttr('js-chat-id').text(`${item.web_phone}`))
            } else {
              _target.text(`${item.web_name.substr(0,1)}经理 - ${item.region_web_city_id}${item.region_web_area_id}`)
            }
            _target.after(_target.clone().removeAttr('js-chat-id').text(`${item.new_min_lx}~${item.new_max_lx} ${item.new_min_ed}万~${item.new_max_ed}万`))
          })
        })
      })
    })
  }

  // 处理图片链接
  const imgLinkArr = kehuLink.split(',').filter((item)=>{return item !== ''})
  const pb2 = window.__panel_chat_pb2 = $.photoBrowser({
    items: imgLinkArr,
    // 某种情况下大图有可能导致微信崩溃，看滑回去能不能解决问题
    // 无论如何安卓就是崩溃……
    onClose: () => {
      // 异步，不堵塞主线程
      setTimeout(() => {
        window.__panel_chat_pb2.slideTo(0, 1)
      }, 0)
    }
  })
  if (imgLinkArr.length > 0) {
    templList += `
      <div class="weui-cell">
        <div class="weui-cell__bd">
          <p>图片资料</p>
        </div>
        <div class="weui-cell__ft" id='photoViewer'>点击浏览</div>
      </div>
    `.trim()
  }
  templList += `
    <div class="weui-cell">
      <div class="weui-cell__bd">
        <p> </p>
      </div>
      <div class="weui-cell__ft">
        <a href="javascript:;" class="weui-btn weui-btn_mini weui-btn_primary" id='js-add_more_kehu_picture'>补充图片</a>
      </div>
      <div style='display:none;'>
        <input type='file' id='js-add_more_img_input' accept='image/*' name='添加图片资料，不可见按钮' form='not_submit'>
      </div>
    </div>
  `
  $(`#panel_data_container`).append(templList)
  if (imgLinkArr.length > 0) {
    $(`#photoViewer`).on('click', {photoView: pb2}, (evt) =>{
      evt.data.photoView.open()
      // pb2.close()
    })
  }

  // 添加图片
  $('#js-add_more_img_input').on({change: fileUploadHandle},{})
  $('#js-add_more_kehu_picture').on({touchend: addMorePictureHandle}, {})


  // 处理头像文字
  $('.person_logo .name').each((index, item) => {
    $(item).text($(item).text().substr(0,1))
  })
  // 发送信息
  $('#sendMessage').on('click', (evt) => {
    const ajaxURL = String($(`#postMessage`).val())
    const phpVar = JSON.parse(window.fromPHP)
    const messageFrom = phpVar.from_user_group_id
    const messageTo = String($(`#choseAnother input`).val())
    const chatID = String($('#getRoomID').val())
    const messageContent = $('#messageInput').text()
    if( messageTo === '' || messageTo === undefined ) {
      $.toptip(`请先选择接受消息的渠道`, 'error')
      throw new Error(`请先选择接受消息的渠道`)
    }
    if( messageContent === '' || messageContent === undefined ) {
      $.toptip(`请先填写消息`, 'error')
      throw new Error(`请先填写消息`)
    }
    const ajaxData = {
      from_user: messageFrom,
      to_user: messageTo,
      chat_id: chatID,
      msg: messageContent
    }
    $.ajax(ajaxURL, {
      method: 'post',
      data: ajaxData,
      beforeSend: () => {
        $.toptip(`正在发送消息`, 'success')
      }
    }).fail((err) => {
      $.toptip(`消息发送失败，请检查网络`, 'error')
    }).done((res) => {
      if (res.code && String(res.code) !== '1') {
        // 失败
        $.toptip(`消息发送失败，服务器返回: ${res.message}`, 'error')
        console.error(`消息发送失败，服务器返回: ${res.message}`)
      } else if (res.code === undefined) {
        // 失败
        $.toptip(`消息发送失败，服务器返回未知格式`, 'error')
        console.error(`消息发送失败，服务器返回: ${res}`)
      }
    }).done((res) => {
      // 成功
      // 生成聊天框
      const date = new Date()
      const year = date.getFullYear()
      const month = date.getMonth()+1
      const day = date.getDate()
      const hour = date.getHours()
      const minute = date.getMinutes()
      const second = date.getSeconds()
      const messageToName = $(`.qudaoListItem[inori-id='${messageTo}']`).text()
      const dateString = `${year}/${month}/${day} ${hour}:${minute}`
      const toQudaomessageBlockTempl = `
        <div class="messageBlock">
          <div class="person_logo">
            <div class="name my_name">我</div>
          </div>
          <div class="message_main_block">
            <div class="person_name">我</div>
            <div class="person_name anjie_from">${window.from_wechat_gongzong}</div>
            <div class="his_name">${messageToName}</div>
            <div class="message_content">${messageContent}</div>
            <div class="message_time">${dateString}</div>
          </div>
        </div>
      `.trim()
      $('.messageContainer').append(toQudaomessageBlockTempl)
      // 计算所有对话框的高度，高度*2作为滚动距离，保证滚动到末尾
      let scrollLength = 0
      $('.message_main_block').each((index, item) => {
        scrollLength += $(item).height()
      })
      $('.messageContainer').scrollTop(scrollLength * 10086)
      // 清除消息框
      $(`#messageInput`).text(null)
    })
  })

  // 选人
  $(`#choseAnother`).on('click', (evt) => {
    evt.preventDefault()
    if(window.__fetching_qudoaList && `${window.__fetching_qudoaList}` !== 'false'){
      $.toptip('正在请求渠道数据，请稍候', 'success')
      return
    }
    const ajaxURL = String($(`#getQudaoList`).val())
    const ajaxData = {
      chat_id: String($(`#getRoomID`).val())
    }

    new Promise((resolve, reject) => {
      $.ajax(ajaxURL, {
        method: 'post',
        data: ajaxData,
        timeout: 3000,
        beforeSend: () => {
          $.toptip('正在获取用户列表', 'success')
          window.__fetching_qudoaList = true
        }
      }).fail((err, errType) => {
        window.__fetching_qudoaList = false
        let Err = {}
        if (`${errType}` === 'timeout') Err = new Error(`timeout`)
        else Err = err
        reject(Err)
      }).done((res) => {
        if (res.code && String(res.code) !== '1') {
          // 失败
          $.toptip(`人员列表获取失败，服务器返回: ${res.message}`, 'error')
          console.error(`人员列表获取失败，服务器返回: ${res.message}`)
          reject(new Error(`人员列表获取失败，服务器返回: ${res.message}`))
        } else if (res.code === undefined) {
          // 失败
          $.toptip(`人员列表获取失败，服务器返回未知格式`, 'error')
          console.error(`人员列表获取失败，服务器返回: ${res}`)
          reject(new Error(`人员列表获取失败，服务器返回: ${res}`))
        }
      }).done((res) => {
        $.toptip("服务器响应成功，正在处理。。。", 'success')
        // 修改替换渠道列表
        $('#qudaoList').empty()
        /**
         * 默认有一个加号列表项
         */
        let qudaoList = `
          <div class="weui-cell js-click_jump_pro_list">
            <div class="weui-cell__bd">
              <p style='text-align:center;'>点我添加渠道</p>
            </div>
            <div class="weui-cell__ft"></div>
          </div>`
        // 如果没有列表就直接弹出
        if (res.data.length === 0) {
          $.toptip(`请在产品页面先选择渠道人员`, 'warning')
          // console.error(`人员列表获取异常，请在产品页面先选择渠道人员`)
          $('#qudaoList').append(qudaoList)
          // 挂点击事件
          $(`#qudaoList .js-click_jump_pro_list`).on('click', (evt) => {
            evt.preventDefault()
            // closePopup() 莫名其妙会产生bug，导致使用之后页面的点击事情无法响应
            $.closePopup()
            // 发送消息到父框架，通知跳转产品列表页面
            // 似乎是跳转后父页面点击事件导致的……
            setTimeout(() => {window.top.postMessage({jumpTo: 'true'}, '*')}, 500)
          })
          $('#qudaoListPopup').popup()
          window.__fetching_qudoaList = false
          return
        }
        const peopleList = res.data
        let uniPeopleList = []
        // 异步数组
        let promiseArrayObj = {
          promiseArrayPro: [],
          promiseArrayQudao: []
        }
        // 去重
        $.each(peopleList, (index, item) => {
          if(uniPeopleList.findIndex((value) => String(value.cg_id) === String(item.cg_id)) === -1) uniPeopleList.push(item)
        })
        $.each(uniPeopleList, (index, item) => {
          const templ = `
            <div class="weui-cell qudaoListItem" qudao-loca='${item.region_web_area_id}' qudao-goods-id='${item.goods_id}' inori-id='${item.to_user_group_id}' inori-name-first='${item.web_name.substr(0,1)}'>
              <div class="weui-cell__bd">
                <p>${item.web_name.substr(0,1)}经理 - ${item.region_web_area_id}</p>
              </div>
              <div class="weui-cell__ft"></div>
            </div>
          `.trim()
          qudaoList += templ
          // 产品id换产品信息
          promiseArrayObj.promiseArrayPro.push( new Promise((resolve, reject) => {
            $.ajax(String($(`#ajax_leaxnm`).val()), {
              data: {gid: `${item.goods_id}`},
              timeout: 1500, //超时时间设置，单位毫秒
              beforeSend: () => {
                if (window.__currentFetchQudaoList) clearTimeout(window.__currentFetchQudaoList)
                if (window.__currentFetchQudaoListIndex) {
                  window.__currentFetchQudaoListIndex = ++window.__currentFetchQudaoListIndex
                } else {
                  window.__currentFetchQudaoListIndex = 1
                }
                window.__currentFetchQudaoList = setTimeout(() => {
                  $.toptip(`正在获取第${window.__currentFetchQudaoListIndex}个渠道的产品利息信息`, 'success')
                }, 300)
              }
            }).fail((err, errType) => {
              if (`${errType}` === 'timeout') reject(new Error(`timeout`))
              else reject(err)
            }).done((res) => {
              if(!res.code || `${res.code}` !== '1') {
                reject(new Error(JSON.stringify(res)))
              } else (
                resolve(res)
              )
            })
          }) )
        })
        $('#qudaoList').append(qudaoList)
        // 挂点击事件
        $(`#qudaoList .js-click_jump_pro_list`).on('click', (evt) => {
          evt.preventDefault()
          // closePopup() 莫名其妙会产生bug，导致使用之后页面的点击事情无法响应
          $.closePopup()
          // 发送消息到父框架，通知跳转产品列表页面
          // 似乎是跳转后父页面点击事件导致的……
          setTimeout(() => {window.top.postMessage({jumpTo: 'true'}, '*')}, 500)
        })
        // 挂点击事件
        $(`#qudaoList .qudaoListItem`).each((index, item) => {
          $(item).on('click', (evt) => {
            const nameFirst = $(evt.target).closest('.qudaoListItem').attr(`inori-name-first`)
            $(`#choseAnother .send_to_person`).text(`${nameFirst}`)
            $(`#choseAnother input`).val(`${String($(evt.target).closest('.qudaoListItem').attr('inori-id'))}`)
            $.closePopup()
          })
        })
        // 辅助关闭弹层……ios下莫名其妙不能关闭弹层了
        $(`#qudaoListPopup .weui-popup__overlay`).off('click')
        $(`#qudaoListPopup .weui-popup__overlay`).on('click', () => {
          $.closePopup()
        })
        resolve(promiseArrayObj)
      })
    }).then( (promiseObj) => {
      return Promise.all(promiseObj.promiseArrayPro).then((dataArray) => {
        $.each(dataArray, (index, item) => {
          if (item.data === null) {
            $(`#qudaoList .qudaoListItem:eq(${index}) p`).append(`<span class='smaller_text' style='display:inline-block;transform:scale(0.8);transform-origin:center bottom;'></span>`)
            $(`#qudaoList .qudaoListItem:eq(${index}) p span`).text(` 0.00~0.00 0万~0万`)
            return
          }
          const id = item.data.goods_id
          $(`#qudaoList .qudaoListItem[qudao-goods-id='${id}'] p`).append(`<span class='smaller_text' style='display:inline-block;transform:scale(0.8);transform-origin:center bottom;'></span>`)
          $(`#qudaoList .qudaoListItem[qudao-goods-id='${id}'] p span`).text(` ${item.data.new_min_lx}~${item.data.new_max_lx} ${item.data.new_min_ed}万~${item.data.new_max_ed}万`)
        })
      }).catch(err => {
        window.__fetching_qudoaList = false
        debugger
      })
    }).then( _ => {
      window.__fetching_qudoaList = false
      $.toptip('清选择聊天渠道', 'success')
      $('#qudaoListPopup').popup()
    }).catch(err => {
      window.__fetching_qudoaList = false
      if (err.message === 'timeout') {
        window.__fetching_qudoaList = false
        $.toptip('网络状况不佳，请检查网络后重试', 2000, 'success')
        // setTimeout(() => {
        //   location.reload(true)
        // }, 1500)
        return
      }
      $.toptip('读取渠道展示消息出错，请稍后重试', 'error')
      console.log(err)
    })
  })
})